#include "dragbutton.h"

DragButton::DragButton(QWidget *parent)
    : TouchButton(parent)
    , m_bPressed(false) // 初始化拖动状态为 false
    , m_bDraged(false)
{
    setText("拖动按钮"); // 设置按钮默认文本
}

// 鼠标按下事件
void DragButton::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_bPressed = true;
        m_dragStartPos = event->pos(); // 记录鼠标按下时的位置
        m_buttonStartPos = this->pos(); // 记录按钮的初始位置
    }
    QPushButton::mousePressEvent(event);
}

// 鼠标移动事件
void DragButton::mouseMoveEvent(QMouseEvent *event)
{
    if (m_bPressed) {
        QPoint offset = event->pos() - m_dragStartPos; // 计算鼠标移动的偏移量
        QPoint newPos = m_buttonStartPos + offset;     // 计算按钮的新位置

        // 限制按钮在父窗口范围内移动
        if (parentWidget()) {
            QRect parentRect = parentWidget()->rect();
            newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - this->width())));
            newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - this->height())));
        }

        move(newPos); // 移动按钮到新位置
        m_buttonStartPos = newPos;
        m_bDraged = true;
    }
   // QPushButton::mouseMoveEvent(event);
}

// 鼠标释放事件
void DragButton::mouseReleaseEvent(QMouseEvent *event)
{
    if(!m_bDraged)
        QPushButton::mouseReleaseEvent(event);
    if (event->button() == Qt::LeftButton) {
        m_bPressed = false; // 停止拖动
        m_bDraged = false;
    }
}
